#!/usr/bin/python3
from iClouds.header import *
from iClouds.rebot import myREBOT
from iClouds.maps import maplist, creatMaps
from iClouds.tools import *
import time
import threading


class roomManager(threading.Thread):
    def __init__(self, name, mode=0, damage=0, group=[1, 2], maps=None):
        threading.Thread.__init__(self)
        self.isRun = True  # 是否运行
        self.sleep = 3  # 等待时间
        self.name = name  # 名称
        self.mode = mode  # 0 合作模式; 1 对抗模式
        self.group = group  # 阵营[1,2]
        self.damage = damage  # 0关闭友军伤害，1开启友军伤害
        self.chat = set()  # 聊天室
        self.allow = 2  # AI同时出现的数量
        self.flag_atack = [(0, 10), (0, 11), (1, 10), (1, 11)]  # 进攻基地位置范围
        self.flag_range = [(20, 10), (20, 11), (21, 10), (21, 11)]  # 守方基地位置范围
        self.max_player = 10  # 最大玩家数量

        self.guid = ""
        self.status = "wait"  # 状态
        self.total = 0  # AI总数量
        self.map = None  # 默认地图
        self.ontime = None  # 开始时间
        self.outtime = None  # 结束时间
        self.flbg = 30  # 攻方军旗血量
        self.flag = 30  # 守方军旗血量
        self.ai = set()  # AI列表

        # # 初始化
        # self.initialization()

    def stop(self):
        self.isRun = False
        print(f"{self.name} is closed...")

    def initialization(self, maps=None):
        """初始化"""
        for i in self.ai:
            i.stop()
            i.join()
        self.guid = str(header_has_guuid())
        self.flbg = 30
        self.flag = 30
        self.total = 20
        self.status = "wait"  # 状态
        self.ontime = None
        self.outtime = None
        # self.map = self.loadMapsInfo(maps)

        # # 创建攻方基地
        # self.map["data"][0][10] = 9
        # self.map["data"][0][11] = 9
        # self.map["data"][1][10] = 9
        # self.map["data"][1][11] = 9
        # # 创建守方基地
        # self.map["data"][20][10] = 9
        # self.map["data"][20][11] = 9
        # self.map["data"][21][10] = 9
        # self.map["data"][21][11] = 9
        # print("\r战场初始化完成...")

    def run(self):
        print(f"{self.name} Room is Run...")
        while self.isRun:
            time.sleep(1)
            if self.status == "wait":
                if self.checkPlayerStatus():
                    self.status = "lock"
                    self.changePlayerStatus("lock")
                    msg = {
                        "act": "lock",
                        "guid": "room",
                        "data": self.sleep,
                    }
                    self.alertAIring(msg)
                    time.sleep(1)
                    # for i in range(len(self.map["data"])):
                    #     time.sleep(0.2)
                    #     msg = {
                    #         "act": "map",
                    #         "guid": "room",
                    #         "code": 200,
                    #         "data": {"index": i, "data": self.map["data"][i]},
                    #     }
                    #     self.alertAIring(msg)

            if self.status == "lock":
                for i in range(self.sleep):
                    self.alertAIring(
                        {"act": "lock", "guid": "room", "data": self.sleep - i}
                    )
                    time.sleep(1)
                # 开始战斗
                self.status = "fight"
                self.ontime = time.time()
                self.changePlayerStatus("fight")
                self.alertAIring({"act": "fight", "guid": "room"})
                # # 开启空袭
                # bomb_cfg = self.map["Bomb"]
                # bomb_cfg["room"] = self
                # bomb = threading.Thread(target=Bomb, kwargs=bomb_cfg)
                # bomb.start()
                # # 开启空投
                # prop_cfg = {}
                # prop_cfg["bound"] = self.map["size"]
                # prop_cfg["room"] = self
                # prop_cfg["sleep"] = 10
                # prop = threading.Thread(target=Prob, kwargs=prop_cfg)
                # prop.start()

            if self.status == "fight":
                if not len(self.chat):
                    self.outtime = time.time()
                    self.initialization()

                # elif self.mode < 1:
                #     self.enableAiPlayer()
                #     if not len(self.ai):
                #         self.gameOver()
                # if self.flag <= 0:
                #     self.gameOver()

    def gameOver(self):
        """结束战斗"""
        # for i in self.chat:
        #     if i.group == 1:
        #         i.snedMessage(
        #             {
        #                 "act": "win" if self.flag > 0 else "lose",
        #                 "guid": "room",
        #                 "code": 200,
        #             }
        #         )
        #     if i.group == 2:
        #         i.snedMessage(
        #             {
        #                 "act": "win" if self.flag <= 0 else "lose",
        #                 "guid": "room",
        #                 "code": 200,
        #             }
        #         )
        if self.status == "wait":
            return
        self.alertAIring({"act": "win", "guid": "room"})
        self.outtime = time.time()
        # self.report()
        self.initialization()

    def result(self, data):
        """得分统计"""
        point = 0
        point += data.get("Lethality", 0) * 3  # 对敌方单位的伤害 数值t65
        point += data.get("damage_zhongli", 0) * 1  # 对中立单位的伤害 数值
        point += data.get("damage_youjun", 0) * 1  # 自己承受的伤害 数值
        point += data.get("kill_diren", 0) * 100  # 击杀敌方单位 次数
        point += data.get("kill_zhongli", 0) * 10  # 击杀中立单位 次数
        point -= data.get("kill_youjun", 0) * 200  # 自己损毁     次数
        point += data.get("box_tmp", 0) * 10  # 空投物资 次数
        point += data.get("box_item", 0) * 5  # 使用道具数 次数
        point += data.get("restore", 0) * 5  # 自己的恢复 数值
        point += data.get("flag", 0) * 200  # 摧毁军旗 数值
        point += math.ceil(data.get("duration", 0))  # 战斗时长 秒数
        return point

    def report(self):
        """战绩统计"""
        data = []
        for i in self.chat:
            x = i.battle
            x["room"] = self.guid
            x["guid"] = i.guid
            x["start"] = self.ontime
            x["end"] = self.outtime
            x["name"] = "玩家没有名字"
            x["score"] = self.result(x)
            data.append(x)
        self.alertAIring({"act": "battle", "guid": "room", "data": data})

    def loadMapsInfo(self, maps):
        """加载地图"""
        themap = maplist.get(maps)
        if not themap:
            return {
                "name": "随机地图",
                "size": [22, 22],
                "Bomb": {"bound": [30, 60], "power": [60, 150]},
                "data": creatMaps(),
            }
        else:
            return themap

    def enableAiPlayer(self):
        """开启AI玩家"""
        if self.total:
            if len(self.ai) < self.allow:
                bot = myREBOT(self)
                bot.start()
                self.ai.add(bot)
                self.total -= 1

    def checkPlayerStatus(self):
        """检测玩家状态是否就绪"""
        if not len(self.chat):
            return False
        status = True
        for i in self.chat:
            if i.status == "wait":
                status = False
        return status

    def changePlayerStatus(self, status):
        """修改玩家状态"""
        for i in self.chat:
            i.status = status

    def alertAIring(self, data):
        """广播消息"""
        for player in self.chat:
            player.snedMessage(data)
